package com.xy.smartsms.db.carrierparam.entity;

import android.content.ContentValues;
import android.content.Context;

import com.xy.smartsms.db.base.MixCursor;
import com.xy.smartsms.db.carrierparam.CarrierDBManager;
import com.xy.smartsms.util.Log;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by kangwenbo on 2017/3/28.
 */

public class OnlineConfigDb {
    private Context mContext;
    //----- 建表 Start------ //
    public static final String KEY_ID = "_id";
    public static final String KEY_LAST_UPDATE_TIME = "last_update_time";
    public static final String KEY_LAST_UPDATE_STATUS = "last_update_status";
    public static final String KEY_VERSION = "param_version";
    public static final String KEY_MAP_KEY = "param_key";
    public static final String KEY_MAP_VALUE = "param_value";
    public static final String KEY_EXTEND = "param_extend_value";

    public static final String NAME = "tb_online_config";

    public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + NAME;
    public static final String CREATE_TABLE = "create table  if not exists "
            + NAME +
            " ("
            + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_MAP_KEY + " TEXT,"
            + KEY_MAP_VALUE + " TEXT,"
            + KEY_EXTEND + " TEXT,"
            + KEY_VERSION + " VARCHAR,"
            + KEY_LAST_UPDATE_TIME + " LONG,"
            + KEY_LAST_UPDATE_STATUS + " INTEGER"
            + ")";

    //----- 建表 end------ //

    private final String TAG = "OnlineConfigDb";

    private static OnlineConfigDb sBlackListManager = null;

    private OnlineConfigDb(Context context) {
        mContext = context;
    }
    public static OnlineConfigDb getInstance() {
        return sBlackListManager;
    }

    public static OnlineConfigDb getInstance(Context context) {
        synchronized (OnlineConfigDb.class) {
            if (sBlackListManager == null) {
                sBlackListManager = new OnlineConfigDb(context);
            }
        }
        return sBlackListManager;
    }

    public void insertOrSkip(OnlineConfigItem item) {
        Log.v(TAG, "insert config msg start " + item.toString());
        MixCursor cursor = null;
        try {
            cursor = CarrierDBManager.query(mContext, NAME,
                    null,
                    KEY_MAP_KEY + "=?",
                    new String[]{item.getKey()});
            if (cursor == null || (cursor != null && cursor.moveToFirst())) {
                return;
            }
            //若查不到数据才执行插入数据，否则会导致数据重复
            CarrierDBManager.insert(mContext, NAME, item.getContentValues());
            Log.v(TAG, "insert config msg success " + item.getKey());
        } catch (Throwable t) {
            Log.e(TAG, "insertOrSkip", t);
        } finally {
            MixCursor.closeCursor(cursor, true);
        }
    }

    public void updateOrInsert(OnlineConfigItem item, ContentValues values) {
        try {
            Log.d(TAG, "config item=" + item);
            int rows = CarrierDBManager.update(mContext, NAME,
                    values,
                    KEY_MAP_KEY + "=?",
                    new String[]{item.getKey()});
            if (rows <= 0) {
                CarrierDBManager.insert(mContext, NAME, values);
            }
        } catch (Throwable t) {
            Log.e(TAG, "updateOrInsert", t);
        }
    }

    public OnlineConfigItem queryByKey(String key) {
        MixCursor cursor = null;
        OnlineConfigItem item = null;
        try {
            cursor = CarrierDBManager.query(mContext, NAME, null, KEY_MAP_KEY + "=?",
                    new String[]{key});
            if (cursor != null && cursor.moveToFirst()) {
                item = new OnlineConfigItem();
                item.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID)));
                item.setKey(cursor.getString(cursor.getColumnIndex(KEY_MAP_KEY)));
                item.setValue(cursor.getString(cursor.getColumnIndex(KEY_MAP_VALUE)));
                item.setExtend(cursor.getString(cursor.getColumnIndex(KEY_EXTEND)));
                item.setVersion(cursor.getString(cursor.getColumnIndex(KEY_VERSION)));
                item.setLastUpdateTime(cursor.getLong(cursor.getColumnIndex(KEY_LAST_UPDATE_TIME)));
                item.setLastUpdateStatus(cursor.getInt(cursor.getColumnIndex(KEY_LAST_UPDATE_STATUS)));
            }
        } catch (Throwable t) {
            Log.e(TAG, "queryByKey", t);
        } finally {
            MixCursor.closeCursor(cursor, true);
        }
        return item;
    }

    /**
     * 获取所有的表数据
     */

    public Map<String, OnlineConfigItem> getAllConfigData() {
        Map<String, OnlineConfigItem> map = new HashMap<String, OnlineConfigItem>();
        MixCursor cursor = null;
        try {
            cursor = CarrierDBManager.query(mContext, NAME, null, null, null);
            if (cursor != null) {
                int id = cursor.getColumnIndex(KEY_ID);
                int key = cursor.getColumnIndex(KEY_MAP_KEY);
                int value = cursor.getColumnIndex(KEY_MAP_VALUE);
                int extend = cursor.getColumnIndex(KEY_EXTEND);
                int version = cursor.getColumnIndex(KEY_VERSION);
                int lastUpdateTime = cursor.getColumnIndex(KEY_LAST_UPDATE_TIME);
                int lastUpdateStatus = cursor.getColumnIndex(KEY_LAST_UPDATE_STATUS);
                while (cursor.moveToNext()) {
                    OnlineConfigItem item = new OnlineConfigItem();
                    item.setId(cursor.getInt(id));
                    item.setKey(cursor.getString(key));
                    item.setValue(cursor.getString(value));
                    item.setExtend(cursor.getString(extend));
                    item.setVersion(cursor.getString(version));
                    item.setLastUpdateTime(cursor.getLong(lastUpdateTime));
                    item.setLastUpdateStatus(cursor.getInt(lastUpdateStatus));
                    map.put(item.getKey(), item);
                }
            }

        } catch (Throwable t) {
            Log.e(TAG, "getAllConfigData", t);
        } finally {
            MixCursor.closeCursor(cursor, true);
        }
        return map;
    }

    public String getMaxVersion() {
        MixCursor cursor = null;
        String version = "1";
        try {
            cursor = CarrierDBManager.query(mContext, NAME, null, null, null, null, null, KEY_VERSION + " desc ", "1");
            if (cursor != null) {
                if (cursor.moveToFirst())
                    version = cursor.getString(cursor.getColumnIndex(KEY_VERSION));
            }

        } catch (Throwable t) {
            Log.e(TAG, "getMaxVersion", t);
        } finally {
            MixCursor.closeCursor(cursor, true);
        }
        return version;
    }

}
